package com.jw.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jw.handler.BusinessException;
import com.jw.response.ResultCode;
import com.jw.system.entity.*;
import com.jw.system.entity.vo.ContractVO;
import com.jw.system.entity.vo.GoodsInVO;
import com.jw.system.entity.vo.GoodsVO;
import com.jw.system.entity.vo.UserVO;
import com.jw.system.mapper.*;
import com.jw.system.service.AliOssService;
import com.jw.system.service.ContractService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jw.system.service.GoodsService;
import com.jw.system.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 合同表 服务实现类
 * </p>
 *
 * @author jw
 * @since 2021-04-20
 */
@Service
public class ContractServiceImpl extends ServiceImpl<ContractMapper, Contract> implements ContractService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private ContractMapper contractMapper;

    @Autowired
    private ConGoodsMapper conGoodsMapper;

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private GoodsOutMapper goodsOutMapper;

    @Autowired
    private OutInfoMapper outInfoMapper;

    @Autowired
    private AliOssService aliOssService;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private UserService userService;

    @Override
    public Page<ContractVO> getConList(Integer current, Integer size, int audit,ContractVO contractVO ,Long userId,Integer userType) {
        Page<Contract> page = new Page<>(current, size);
        QueryWrapper<Contract> queryWrapper = new QueryWrapper();
        //请求用户为客户
        if(userType==0){
            queryWrapper.eq("cus_id",userId);
        }
        if(userType==1){
            queryWrapper.eq("user_id",userId);
        }
        //模糊查询客户名
        if (contractVO.getCusName() != null) {
            QueryWrapper<Customer> queryCus = new QueryWrapper();
            queryCus.like("username", contractVO.getCusName());
            List<Customer> customerList = customerMapper.selectList(queryCus);
            if (!customerList.isEmpty()) {
                List<Long> list = new ArrayList<>();
                for (Customer customer : customerList) {
                    list.add(customer.getId());
                }
                queryWrapper.in("cus_id", list);
            } else {
                return new Page<>();
            }
        }

        //模糊查询员工名
        if (contractVO.getUsername() != null) {
            QueryWrapper<User> queryUser = new QueryWrapper();
            queryUser.like("username", contractVO.getUsername());
            List<User> userList = userMapper.selectList(queryUser);
            if (!userList.isEmpty()) {
                List<Long> list = new ArrayList<>();
                for (User user : userList) {
                    list.add(user.getId());
                }
                queryWrapper.in("user_id", list);
            } else {
                return new Page<>();
            }
        }
        //模糊查询合同编号
        if (contractVO.getConNum() != null) {
            queryWrapper.like("con_num", contractVO.getConNum());
        }
        if (contractVO.getStartTime() != null) {
            queryWrapper.ge("date", contractVO.getStartTime());
            queryWrapper.le("date", contractVO.getEndTime());
        }

        if (contractVO.getStaus() != null) {
            queryWrapper.eq("staus", contractVO.getStaus());
        }
        // 1合同管理页面 2合同审核页面 3合同订单发货页面
        if(audit==2){
            queryWrapper.eq("staus", -1);
        }
        if(audit==3){
            queryWrapper.ne("staus", -1);
        }
        Page<Contract> contractPage = contractMapper.selectPage(page, queryWrapper);
        List<ContractVO> contractVOS = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (Contract contract : contractPage.getRecords()) {
            ContractVO contractVO1 = new ContractVO();
            BeanUtils.copyProperties(contract, contractVO1);
            contractVO1.setCusName(customerMapper.selectById(contract.getCusId()).getUsername());
            contractVO1.setUsername(userMapper.selectById(contract.getUserId()).getUsername());
            contractVO1.setAuditorName(userMapper.selectById(contract.getAuditorId()).getUsername());
            contractVO1.setSalesmanName(userMapper.selectById(contract.getSalesmanId()).getUsername());
            contractVO1.setDate(sdf.format(contract.getDate()));
            contractVO1.setDeadline(sdf.format(contract.getDeadline()));
            if (contract.getFinishDate() != null) {
                contractVO1.setFinishDate(sdf.format(contract.getFinishDate()));
            }
            contractVO1.setDeadDays(((contract.getDeadline().getTime() - contract.getDate().getTime()) / (1000 * 3600 * 24)));
            contractVOS.add(contractVO1);
        }
        Page<ContractVO> contractVOPage = new Page<>();
        contractVOPage.setRecords(contractVOS);
        contractVOPage.setTotal(contractPage.getTotal());
        return contractVOPage;
    }

    @Override
    public Page<GoodsVO> getDetail(Integer current, Integer size, Long id, Goods goodsQuery) {
        List<Goods> goodsList = goodsService.getGoodsList(1, goodsMapper.selectCount(null), goodsQuery).getRecords();
        if (CollectionUtils.isEmpty(goodsList)) {
            return new Page<>();
        }
        List<Long> idList = new ArrayList<>();
        for (Goods goods : goodsList) {
            idList.add(goods.getId());
        }
        Page<ConGoods> page = new Page<>(current, size);
        QueryWrapper<ConGoods> queryWrapper = new QueryWrapper();
        Contract contract = contractMapper.selectById(id);
        queryWrapper.eq("con_num", contract.getConNum());
        queryWrapper.in("goods_id", idList);
        Page<ConGoods> conGoodsPage = conGoodsMapper.selectPage(page, queryWrapper);
        if (CollectionUtils.isEmpty(conGoodsPage.getRecords())) {
            throw new BusinessException(ResultCode.CONTRACT_DETAIL_NOT_FOUND.getCode(),
                    ResultCode.CONTRACT_DETAIL_NOT_FOUND.getMessage());
        }
        List<GoodsVO> goodsVOList = new ArrayList<>();
        //一个合同可能有多个出库单，每个出库单有对应的明细
        QueryWrapper<GoodsOut> queryGoodsOut = new QueryWrapper();
        queryGoodsOut.eq("con_id", id);
        queryGoodsOut.eq("staus", 2);//出库单状态必须为已发货
        List<GoodsOut> goodsOut = goodsOutMapper.selectList(queryGoodsOut);
        //处理商品明细内容
        for (ConGoods conGoods : conGoodsPage.getRecords()) {
            GoodsVO goodsVO = new GoodsVO();
            Goods goods = goodsMapper.selectById(conGoods.getGoodsId());
            BeanUtils.copyProperties(goods, goodsVO);
            goodsVO.setPrice(conGoods.getPrice());
            goodsVO.setOrderNum(conGoods.getOrderNum());
            //如果出库单不为空
            if (!CollectionUtils.isEmpty(goodsOut)) {
                int finishNum = 0;
                for (GoodsOut out : goodsOut) {
                    //获得出库单对应明细
                    QueryWrapper<OutInfo> queryOutInfo = new QueryWrapper();
                    queryOutInfo.eq("out_num", out.getOutNum());
                    queryOutInfo.eq("goods_id", conGoods.getGoodsId());
                    List<OutInfo> OutInfoList = outInfoMapper.selectList(queryOutInfo);
                    //设置商品已完成数量
                    for (OutInfo outInfo : OutInfoList) {
                        finishNum = finishNum + outInfo.getNum();
                    }
                    goodsVO.setFinishNum(finishNum);
                    if (goodsVO.getFinishNum() >= goodsVO.getOrderNum()) {
                        goodsVO.setStaus(2);
                    } else {
                        goodsVO.setStaus(1);
                    }
                }
            }//已发货出库单为空则商品状态为未发货，已发货数量为0
            else {
                goodsVO.setFinishNum(0);
                goodsVO.setStaus(0);
            }
            NumberFormat numberFormat = NumberFormat.getInstance();
            // 设置精确到小数点后2位
            numberFormat.setMaximumFractionDigits(2);
            String result = numberFormat.format((float)goodsVO.getFinishNum()/(float)goodsVO.getOrderNum()*100);
            goodsVO.setPercent(result+"%");
            goodsVOList.add(goodsVO);
        }
        Page<GoodsVO> goodsVOPage = new Page<>();
        goodsVOPage.setRecords(goodsVOList);
        goodsVOPage.setTotal(conGoodsPage.getTotal());
        return goodsVOPage;
    }

    @Override
    public void upload(Long id, MultipartFile file) {
        SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
        String originName = file.getOriginalFilename();
        //判断文件类型是不是pdf
        if (!originName.endsWith(".pdf")) {
            throw new BusinessException(ResultCode.FILE_TYPE_ERROR.getCode(),
                    ResultCode.FILE_TYPE_ERROR.getMessage());
        }
        //阿里oss存储
        try {
            Contract contract = contractMapper.selectById(id);
            //若有文件则先删除旧文件
            if (contract.getFile() != null) {
                aliOssService.deleteFile(contract.getFile().replaceAll("http://cgm-file.oss-cn-guangzhou.aliyuncs.com/", ""));
            }
            String url = aliOssService.upload(file);
            contract.setFile(url);
            contractMapper.updateById(contract);
        } catch (Exception e) {
            //返回异常
            throw new BusinessException(999, "上传失败");
        }
    }

    @Override
    public ContractVO getConById(Long id) {
        Contract contract = contractMapper.selectById(id);
        if(contract==null){
            throw new BusinessException(ResultCode.CONTRACT_NOT_FOUND.getCode(),
                    ResultCode.CONTRACT_NOT_FOUND.getMessage());
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        ContractVO contractVO1 = new ContractVO();
        BeanUtils.copyProperties(contract, contractVO1);
        contractVO1.setCusName(customerMapper.selectById(contract.getCusId()).getUsername());
        contractVO1.setUsername(userMapper.selectById(contract.getUserId()).getUsername());
        contractVO1.setAuditorName(userMapper.selectById(contract.getAuditorId()).getUsername());
        contractVO1.setSalesmanName(userMapper.selectById(contract.getSalesmanId()).getUsername());
        contractVO1.setDate(sdf.format(contract.getDate()));
        contractVO1.setDeadline(sdf.format(contract.getDeadline()));
        if (contract.getFinishDate() != null) {
            contractVO1.setFinishDate(sdf.format(contract.getFinishDate()));
        }
        contractVO1.setDeadDays(((contract.getDeadline().getTime() - contract.getDate().getTime()) / (1000 * 3600 * 24)));
        return contractVO1;
    }

    @Override
    public void add(ContractVO contractVO) throws ParseException {
        Contract contract = new Contract();
        BeanUtils.copyProperties(contractVO, contract);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        contract.setDate(sdf.parse(contractVO.getDate()));
        contract.setDeadline(sdf.parse(contractVO.getDeadline()));
        contract.setUserId(userService.getUserInfo().getId());
        contract.setStaus(-1);
        String CON_NUM = UUID.randomUUID().toString().substring(0, 16).replace("-", "");
        contract.setConNum(CON_NUM);
        Integer totalPrice = 0;

        List<Object> products = contractVO.getProducts();
        System.out.println(products);
        for (Object product : products) {
            LinkedHashMap item = (LinkedHashMap) product;
            //需求数量
            int productNumber = (int) item.get("productNumber");
            //物资编号
            Integer productId = (Integer) item.get("productId");
            //商品单价
            Integer productPrice = (Integer) item.get("productPrice");
            Goods dbProduct = goodsMapper.selectById(productId);
            if (dbProduct == null) {
                throw new BusinessException(ResultCode.PRODUCT_NOT_FOUND.getCode(),
                        ResultCode.PRODUCT_NOT_FOUND.getMessage());
            } else if (productNumber <= 0) {
                throw new BusinessException(ResultCode.PRODUCT_IN_STOCK_NUMBER_ERROR.getCode(),
                        ResultCode.PRODUCT_IN_STOCK_NUMBER_ERROR.getMessage());
            } else {
                //插入合同明细
                ConGoods conGoods = new ConGoods();
                conGoods.setConNum(CON_NUM);
                conGoods.setGoodsId(dbProduct.getId());
                conGoods.setOrderNum(productNumber);
                conGoods.setPrice(productPrice);
                totalPrice +=productNumber*productPrice;
                conGoodsMapper.insert(conGoods);
            }
        }
        contract.setPrice(totalPrice);
        contractMapper.insert(contract);
    }

    @Override
    public void getApprove(Long id) {
        Contract contract = contractMapper.selectById(id);
        contract.setStaus(0);
        contractMapper.updateById(contract);
    }
}
